//index.js
//获取应用实例
var app = getApp();
//console.log(app.globalData);
Page({
  data: {
    userInfo: {},
    imageList:[],
    imageKeys:[],
    topicType:2,
    groupData:{},
    topicData:{},
    videoSrc:'',
    videoKey:'',
    topic_id:0,
    setDate:0,
    orderListActive:0,
    chooseVideoText:'选择视频',
    status:0,
    content:'',
    //statusArray: ['所有人可参与打卡', '仅自己可打卡'],
    cateArray: ['未开始', '进行中','己完成'],
    cate_id:0,
    remainTypeArray: ['日期', '周'],
    weekList: [],
    weekListStr: [],
    remainType:3,
    startdate: '',
    enddate: '',
    noti:0,
    pidindex:'',
    groupList:[],
    signCount:1,
    averageDay:1,
    signIn:0,
    countArray:[1,2,3,4,5,6,7],
    statusArray: ['公开', '仅自己可看']
  },

  
  switch2Change:function(e){
    var name = e.currentTarget.dataset.type;
    console.log(name);
    if (name =="setDate"){
      console.log(e.detail.value);
      this.setData({ setDate: e.detail.value });
    }else if(name=="signIn"){
      this.setData({ signIn: e.detail.value });
    }
  },
  bindCountChange: function(e) {
    var v = Number(e.detail.value)+1;
    var name = e.currentTarget.dataset.type;
    if (name == "averageDay") {
      this.setData({ averageDay: v });
    } else if (name == "signCount") {
      this.setData({ signCount: v });
    }
  },
  bindTypeChange:function(e){
    this.setData({ pidindex: e.detail.value });
    this.data.pid = this.data.groupList[e.detail.value].id;
    //console.log(this.data.pid);
  },
  //设置时间
  bindDateChange: function (e) {
    var v = e.detail.value;
    var name = e.currentTarget.dataset.name;
   if(name=="enddate"){
     this.setData({ enddate: v });
   }else{
     this.setData({ startdate: v });
   }
    
  },

  reset:function(){
    this.setData ( {
      userInfo: {},
      imageList: [],
      imageKeys: [],
      topicType: 2,
      groupData: {},
      topicData: {},
      videoSrc: '',
      videoKey: '',
      status: 0,
      cate_id: 0,
      content: '',
      weekList: [],
      weekListStr: [],
      remainType: 3,
      time: '',
      disabled:0,
      loading:0,
      pidArray:[],
    });
  },
  bindStatusChange: function (e) {
    var v = Number(e.detail.value);
    this.setData({ status: v });
  },
  onShow:function(){
    
   
  },
  onHide:function(){
    
    app.setPageData("index/issue", { options: null });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var now = new Date();
    var year = now.getFullYear(); //得到年份
    var month = now.getMonth();//得到月份
    var date = now.getDate();//得到日期
    var startYear = year + "-" + month + "-" + date;
    this.setData({ startYear: startYear})
    this.getPidArray();
  },
  getPidArray:function(){
    var that = this;
    app.api("group/get", {
      order: 'orderBy',
      status: 1,
      type: 'todolist',
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      if (res.data.list.length > 0) {
        var pidArray=[];
        for (var i in res.data.list ){
          pidArray.push(res.data.list[i].value);
        }
        that.setData({
          pidArray: pidArray, groupList: res.data.list
        });
      }
    })
  },
  getTopic: function () {
    console.log("getTopic");
    var that = this;
    var pid = this.data.pid2;
    var topic_id = this.data.topic_id;
    var id = topic_id ? topic_id : pid;
    app.api("topic/detail", {
      id: id,
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      that.setData({ topicData: res.data ,pid:res.data.pid});
      if (topic_id>0){
       // console.log("324234",res.data);
        that.setData({
          imageList: res.data.pics,
          imageKeys: res.data.imageKeys,
          videoSrc: res.data.video_url,
          videoKey: res.data.videoKey,
          content: res.data.title,
          status: Number(res.data.status)-1
         });
         if(res.data.pid2>0){
           that.setData({ topicType: 1});
         }
      }
    })
  },


  //
  getGroup: function () {
    var that = this;
    var pid = this.data.pid;
    app.api("group/find", {
      id: pid
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      that.setData({ groupData: res.data });
      //主题只能参与一次，那么直接发动态了
      if (res.data.content.joinLimit == 1 && res.data.joined.code == 0 && that.data.pid2==0){
        var topicData = res.data.joined.data;
        that.setData({ topicData: topicData, pid2: topicData.id, topicType: 1});
        wx.setNavigationBarTitle({
          title: '创建小计划'
        });
      }else{
        wx.setNavigationBarTitle({
          title: res.data.content.issuePageTitle
        });
      }
    })
  },
  delImgVideo:function(){
    this.setData({
      videoSrc: '',
      videoKey: '',
    })
  },
  choose:function(){
    var that = this;
    console.log("videoSrc",this.data.videoSrc);
    if (this.data.videoSrc.length > 0 && this.data.imageKeys.length == 0){
      that.chooseImage();
      return ;
    }
    if (this.data.imageKeys.length>1){
      that.chooseImage();
      return ;
    }
    
    wx.showActionSheet({
      itemList: ['上传图片', '上传视频'],
      success: function (res) {
        if (res.tapIndex==0){
          that.chooseImage();
        } else if (res.tapIndex == 1){
          that.chooseVideo();
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  chooseVideo: function () {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function (res) {
        var filePath = res.tempFilePath;
        that.setData({ chooseVideoText: '上传中...' });
        app.upload(filePath, (res) => {
          console.log(res);
          that.setData({ chooseVideoText: '选择视频' });
          that.setData({
            videoSrc: res.imageURL,
            videoKey:res.key,
          })
        })

      }
    })
  },

  chooseImage:function(){
    var that = this
    var imageList = this.data.imageList;
    var imageKeys = this.data.imageKeys;
    // if (this.data.topicType == 2) {
    //   var max = 3 - this.data.imageList.length;
    // } else {
    //   var max = 1;
    // }
    var max = 3 ;
    console.log(this.data.videoSrc);
    //上传了视频那只能上传一张图片 
    if (this.data.videoSrc.length > 0) {
      var max = 1;
    }
    wx.chooseImage({
      sizeType: 'compressed',
      count: max,
      success: function (res) {
        var newImages = res.tempFilePaths;
        for (var i in newImages){
          var filePath = newImages[i];
          app.upload(filePath, (res) => {
            imageList = imageList.concat(res.imageURL);
            imageKeys = imageKeys.concat(res.key) ;
            that.setData({ imageList: imageList, imageKeys: imageKeys});
          })
        }
      }
    })
  },
  delImg:function(e){
    var id = e.currentTarget.dataset.id;
    var imageList = this.data.imageList;
    var imageKeys = this.data.imageKeys;
    imageList.splice(id, 1);
    imageKeys.splice(id, 1);
    this.setData({ imageList: imageList, imageKeys: imageKeys});
  },
  //浏览图片
  previewImage: function (e) {
    var current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.imageList
    })
  },

  formSubmit:function(e){
    var that = this;
    var user_info = app.globalData.userInfo;
    var postData = e.detail.value;
    if (this.data.loading == 1) {
      return;
    }
    //console.log(postData);
    //创建心愿单
    if (postData.title == "") {
      app.alert('请先输入计划标题');
      return false;
    }
    if (!this.data.pid){
      app.alert('请先输入计划类型');
      return false;
    }
    if (postData.desc == "") {
      app.alert('请先输入计划内容');
      return false;
    }
    if (this.data.videoSrc.length > 0 && this.data.imageKeys.length == 0) {
      app.alert('添加视频封面图片');
      return false;
    }
    // if (postData.money>0 && !this.maxCount){
    //   app.alert('请设置打卡次数');
    //   return false;
    // }
    that.doformSubmit(e);

    // if (!this.data.signIn){
    //   that.doformSubmit(e);
    //   return;
    // }
    // wx.showModal({
    //   title: '说到做到！',
    //   content: '发布计划后就不能再修改打卡次数，金额，天数了哦,确认发布吗？',
    //   success: function (res) {
    //     if (res.confirm) {
    //       that.doformSubmit(e);
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
  },

  //发布活动 
  doformSubmit: function (e) {
  
    var user_info = app.globalData.userInfo;
    var postData = e.detail.value;
    if (this.data.loading==1){
      return ;
    }
    
    this.setData({ 'loading': 1 });
    this.setData({ 'disabled': 1 });
    var _this = this;
    var contentData = {   
      signIn: this.data.signIn,
      startdate: this.data.startdate,
      enddate: this.data.enddate,
      noti: this.data.noti
    };
    //打卡类型的计划
    if (this.data.signIn){
      contentData.signCount= this.data.signCount;
      contentData.averageDay=this.data.averageDay;
      contentData.days=postData.days;
      contentData.money=this.data.money;
      contentData.startdate = this.data.startdate;
      contentData.enddate = this.data.enddate;
      
    }
    //有设置提醒
    if (this.data.noti) {
      contentData.weekList= this.data.weekList;
      contentData.weekListStr= this.data.weekListStr;
      contentData.remainType= this.data.remainType;
    }

    //提交回答
    app.api("topic/add", {
      title: postData.title,
      desc: postData.desc,
      status: Number(this.data.status)+1,
      pics: this.data.imageKeys.join(","),
      password: postData.password,
      type:'todolist',
      pid:this.data.pid,
      pid2:0,
      video_url: this.data.videoKey,
      content: JSON.stringify(contentData),
      cate_id: this.data.cate_id,
      method: 'POST',
    }, function (res) {
   
      var title = "";
      if (res.code == 200) {
      //发布成生成订单支付
         var topic_id = res.data.id;
         if(_this.data.money>0){
           _this.pay(topic_id);
         }else{
           _this.join_topic(topic_id);
         }
        
      } else {
        _this.setData({ 'loading': 0 });
        _this.setData({ 'disabled': 0 });
        app.alert(res.msg);
      }
    })
  },

  join_topic: function (topic_id){
    var that = this;
    if (that.data.payloading == 1) {
      return false;
    }
    that.data.payloading = 1;
    app.api("topicjoin/join", {
      topic_id: topic_id
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        that.data.payloading = 0;
        that.setData({ 'loading': 0 });
        that.setData({ 'disabled': 0 });
        return false;
      }
      that.suc();
    })
  },
  
  pay: function (topic_id){
    var that =this;
    if (that.data.payloading == 1) {
      return false;
    }
    that.data.payloading =1;
    app.api("pay/topic_join",{
      topic_id:topic_id
    },function(res){
       if(res.code!=200){
         app.alert(res.msg);
         that.data.payloading=0;
         that.setData({ 'loading': 0 });
         that.setData({ 'disabled': 0 });
         return false;
       }
       var order_sn = res.data.order_sn;
       app.api("pay/topay", {
         order_sn: order_sn
       },function(res){
         if (res.code != 200) {
           app.alert(res.msg);
           that.data.payloading = 0;
           that.setData({ 'loading': 0 });
           that.setData({ 'disabled': 0 });
           return false;
         }
         if (res.data.over==1){
           that.suc();
           return;
         }
         var params = res.data;
         //params.total_fee = 0.1;
         params.success = function (res) {
           that.suc();
         }
         params.fail = function (res) {
           console.log(res);
           if (res.errMsg == 'requestPayment:fail cancel') {
            //  wx.navigateBack({
            //    delta: 1
            //  })
             that.setData({ 'loading': 0 });
             that.setData({ 'disabled': 0 });
             return false;
           }
           app.alert(res.errMsg);
         }
         console.log(params);
         wx.requestPayment(params)

       })
    })
  },

  suc:function(){
    var _this =this;
    wx.showToast({
      title: '发布成功',
      icon: 'success',
      duration: 2000
    });
    _this.reset();
    app.setPageData("index/index", { reload: 1 });
    app.setPageData("index/index", { reload2: 1 });
    app.setPageData("group/index", { reload: 1 });
    app.setPageData("user/timeline", { reload: 1 });
    app.setPageData("user/timeline", { reload2: 1 });
    _this.navigateBack();
  },
//返回 
  navigateBack: function (e){
    wx.switchTab({
      url: '/pages/user/timeline'
    });
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  bindRemainTypeChange: function (e) {
    //console.log(e);
    var v = Number(e.detail.value);
    this.setData({ remainType: v });
    if(v==1){
      this.setData({ orderListActive:1});
    }
  },
 
 
  bodyclick() {
    console.log('bodyclick');
    if (this.data.orderListActive == 1) {
      this.setData({ orderListActive: 0 });
    }
  },
  showWeek:function(){
    this.setData({ orderListActive: 1 });
  },
  chooseWeek:function(e){
   var index = app.in_array(e.currentTarget.dataset.key, this.data.weekList)
   if (index===false){
      this.data.weekList.push(e.currentTarget.dataset.key);
      this.data.weekListStr.push(e.currentTarget.dataset.text);
    }else{
     this.data.weekListStr.splice(index, 1);
     this.data.weekList.splice(index, 1);
    }
    this.setData({
      weekList: this.data.weekList,
      weekListStr: this.data.weekListStr
    });
    //console.log(this.data.weekListStr);
  }, 
  bindCateChange: function (e) {
    var v = Number(e.detail.value);
    this.setData({ cate_id: v });
  },
  setMoney:function(e){
    this.data.money = e.detail.value;
    this.setData({ money: e.detail.value});
  },
  aboutmoney:function(){
    // if (!this.data.money || this.data.money<=0){
    //    app.alert("请先设置打卡金，再查看");
    //    return ;
    // }
    var content = "每人加入计划需要支付的金额，完成计划的人可以瓜分总金额";
    wx.showModal({
      title: '嗯，对！钱能使用我自律!',
      content: content,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  
})
